import pickle
import struct
import socket
import threading
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(("127.0.0.1", 9003))


class CClientSocket(object):
    def __init__(self, oSocket):
        self.m_Socket = oSocket
        self.m_MsgBuf = b""
        self.m_SocketLen = 0

    def RecvMsg(self):
        while True:
            if self.m_SocketLen == 0:
                try:
                    self.m_MsgBuf += self.m_Socket.recv(4)
                except:
                    break
                if len(self.m_MsgBuf) >= 4:
                    sLen = self.m_MsgBuf[:4]
                    self.m_MsgBuf = self.m_MsgBuf[4:]
                    iLen = struct.unpack("i", sLen)[0]
                    self.m_SocketLen = iLen
                else:
                    break
            else:
                try:
                    self.m_MsgBuf += self.m_Socket.recv(self.m_SocketLen)
                except:
                    break
                if len(self.m_MsgBuf) >= self.m_SocketLen:
                    sMsg = self.m_MsgBuf[:self.m_SocketLen]
                    self.m_MsgBuf = self.m_MsgBuf[self.m_SocketLen:]
                    self.m_SocketLen = 0
                    oPackage = pickle.loads(sMsg)
                    self.OnCommand(oPackage)
                else:
                    break

    def OnCommand(self, oPackage):
        if oPackage:
            for sMsg in oPackage:
                MsgInfo = pickle.loads(sMsg)
                print(MsgInfo)

oClientSocket = CClientSocket(clientsocket)

class CReceiveThread(threading.Thread):
    def __init__(self, thread_name):
        super(CReceiveThread, self).__init__(name=thread_name)

    def run(self):
        while True:
            oClientSocket.RecvMsg()

oNetWorkThread = CReceiveThread("receive")
oNetWorkThread.start()

while True:
    sMsg = input("what do you want to send?")
    sPackage = pickle.dumps({"msg":sMsg})
    iLen = len(sPackage)
    sBuff = struct.pack("i", iLen) + sPackage
    clientsocket.send(sBuff)